//
//  PhotoBrowserCollectionViewController.swift
//  JKWeiBo
//
//  Created by 王冲 on 2017/12/27.
//  Copyright © 2017年 希爱欧科技有限公司. All rights reserved.
//

import UIKit
import SVProgressHUD
private let PhotoBrowserCollectionReuseIdentifier = "Cell"

class PhotoBrowserCollectionViewController: UIViewController {

    var currentIndex: Int?
    var pictures: [NSURL]?
    
    
    init(index:Int,picurls: [NSURL]) {
      
        // swift语法规定，必须先初始化本类属性，再初始化父类
        currentIndex = index
        pictures = picurls
        
        super.init(nibName: nil, bundle: nil)
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.white
        
        // 初始化
        setUI()
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        self.dismiss(animated: true, completion: nil)
    }
    
    // MARK: 初始化UI
    func setUI() {
        
        self.view.addSubview(self.collectionView)
        self.view.addSubview(self.closeBtn)
        self.view.addSubview(self.saveBtn)
        
        // 1.注册一个cell
        self.collectionView.register(PhotoBrowserCollectionViewCell.self, forCellWithReuseIdentifier: PhotoBrowserCollectionReuseIdentifier)
    }
    
    lazy var closeBtn: UIButton = {
        
        let btn = UIButton(frame: CGRect(x: 30, y: JKscreenH-80, width: 80, height: 50))
        btn.setTitle("关闭", for: UIControlState.normal)
        btn.addTarget(self, action: #selector(PhotoBrowserCollectionViewController.close), for: UIControlEvents.touchUpInside)
        btn.backgroundColor = UIColor.brown
        return btn
        
    }()
    
    lazy var saveBtn: UIButton = {
        
        let btn = UIButton(frame: CGRect(x: JKscreenW-30-80, y: JKscreenH-80, width: 80, height: 50))
        btn.setTitle("保存", for: UIControlState.normal)
        btn.addTarget(self, action: #selector(PhotoBrowserCollectionViewController.save), for: UIControlEvents.touchUpInside)
        btn.backgroundColor = UIColor.brown
        return btn
        
    }()
    
    // MARK: 关闭按钮
    func close() {
        
        self.dismiss(animated: true, completion: nil)
    }
    
    // MARK: 保存按钮
    func save() {
        
       print("保存")
       // 1.拿到当前的cell
        let index = collectionView.indexPathsForVisibleItems.last
        let cell = collectionView.cellForItem(at: index!) as! PhotoBrowserCollectionViewCell
        
        // 2.保存图片
        let image  = cell.iconView.image
     
        UIImageWriteToSavedPhotosAlbum(image!, self, #selector(PhotoBrowserCollectionViewController.image(image:didFinishSavingWithError:contextInfo:)), nil)
    }
    
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    func image(image:UIImage,didFinishSavingWithError error:NSError?,contextInfo:UnsafeRawPointer) {
        
        if error != nil {
            SVProgressHUD.showError(withStatus: "保存失败")
            SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.black)
        } else {
            SVProgressHUD.showSuccess(withStatus: "保存成功")
            SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.black)
        }
    }
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    
    lazy var collectionView: UICollectionView = {
        
        let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: JKscreenW, height: JKscreenH),collectionViewLayout:PhotoBrowserCollectionViewLayout())
        collectionView.backgroundColor = UIColor.white
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.isPagingEnabled = true
        
        return collectionView
 
    }()
    

}

extension PhotoBrowserCollectionViewController: UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,PhotoBrowserCollectionViewCellDelegate
{
    // MARK: - UICollectionViewDataSource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return  pictures?.count ?? 0
    }
    
    func collectionView(_ collectihonView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // 1.取出cell
        let itemCell = collectionView.dequeueReusableCell(withReuseIdentifier: PhotoBrowserCollectionReuseIdentifier, for: indexPath) as! PhotoBrowserCollectionViewCell
        itemCell.backgroundColor = UIColor.JKRandomColor()
        itemCell.imageURL = pictures?[indexPath.item]
        itemCell.photoBrowserDelegate = self
        // 3.返回cell
        return itemCell
    }
    
    // cell里面的代理
    func photoBrowserClose(cell: PhotoBrowserCollectionViewCell)
    {
        close()
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        
        return UIEdgeInsets(top: 0, left:0, bottom: 0, right: 0)
    }
}

